from flask import Flask, request, render_template, redirect, url_for, session, flash, __version__
from admin import admin
import config
from models import User, Column, Blog, Youlian
from werkzeug.utils import secure_filename
import hashlib, os, time
from exts import db
from PIL import Image
import socket

app = Flask(__name__)
app.config.from_object(config)
app.config.update(WEBSITE_NAME=12)
title = app.config['WEBSITE_NAME']


# 网站后台
@admin.route('/')
def admin_index():
    uid = session.get('uid')
    if uid == None:
        return redirect(url_for('admin.admin_login'))
    data = {'title': '后台首页'}
    data['column'] = Column.query.all()
    data['user'] = User.query.first()
    data['blog'] = Blog.query.join(User, Blog.uid == User.id).add_entity(User).all()
    data['flask'] = __version__
    data['hostname'] = socket.gethostname()
    data['ip'] = socket.gethostbyname(data['hostname'])
    return render_template('./admin/index.html', data=data)


# 登录后台
@admin.route('/login/', methods=['GET', 'POST'])
def admin_login():
    if request.method == 'GET':
        return render_template('./admin/login.html')
    else:
        uname = request.form.get('uname')
        password = request.form.get('password')
        password = hashlib.md5(password.encode("utf-8")).hexdigest()
        user = User.query.filter(User.name == uname, User.password == password).first()
        if user:
            session['uid'] = user.id
            session['user'] = user.name
            return redirect(url_for('admin.admin_index'))
        else:
            flash(u'登录失败')
            return render_template('./admin/login.html')


# 栏目管理
@admin.route('/column/', methods=['GET', 'POST'])
def admin_column():
    uid = session.get('uid')
    if uid == None:
        return redirect(url_for('admin.admin_login'))
    if request.method == 'GET':
        data = {}
        data['column'] = Column.query.all()
        if data:
            return render_template('./admin/column.html', data=data)
        else:
            pass
    else:
        pass


# 添加栏目
@admin.route('/column/add/', methods=['GET', 'POST'])
def admin_column_add():
    uid = session.get('uid')
    if uid == None:
        return redirect(url_for('admin.admin_login'))
    if request.method == 'POST':
        title = request.form.get('title')
        fid = request.form.get('fid')
        data = Column()
        data.title = title
        data.fid = fid
        db.session.add(data)
        db.session.commit()
        return redirect(url_for('admin.admin_column'))


# 删除栏目
@admin.route('/column/del/<int:f_id>/')
def admin_column_del(f_id):
    uid = session.get('uid')
    if uid == None:
        return redirect(url_for('admin.admin_login'))
    if f_id != None:
        data = Column.query.filter(Column.id == f_id).first()
        db.session.delete(data)
        db.session.commit()
    return redirect(url_for('admin.admin_column'))


# 发布文章
@admin.route('/fabu/', methods=['GET', 'POST'])
def admin_fabu():
    uid = session.get('uid')
    if uid == None:
        return redirect(url_for('admin.admin_login'))

    if request.method == 'GET':
        data = {'title': '发布博文'}
        data['column'] = Column.query.all()
        if data:
            return render_template('./admin/fabu.html', data=data)
    else:
        title = request.form.get('title')
        intro = request.form.get('intro')
        content = request.form.get('content')
        fid = request.form.get('fid')
        if len(title) != 0 and len(content) != 0:
            if request.files['file']:
                f = request.files['file']
                basepath = os.path.dirname(__file__)  # 当前文件所在路径
                fname = secure_filename(f.filename)
                ext = fname.rsplit('.', 1)[1]  # 获取文件后缀
                unix_time = int(time.time())
                new_filename = str(unix_time) + '.' + ext  # 修改了上传的文件名
                image_path = '../static/uploads/thumbnail/'
                upload_path = os.path.join(basepath, image_path, new_filename)
                file_url = image_path + new_filename
                # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
                f.save(upload_path)
                # 压缩图片   --------以后会整理代码
                file_image = os.path.abspath(os.path.dirname(basepath)) + '/static/uploads/thumbnail/' + new_filename
                img = Image.open(file_image)
                img.resize((128, 128), Image.ANTIALIAS)
                img.save(upload_path)
            else:
                file_url = None
            data = Blog()
            data.title = title
            data.content = content
            data.article_intro = intro
            data.uid = uid
            data.fid = fid
            data.image = file_url
            db.session.add(data)
            db.session.commit()
            return redirect(url_for('admin.admin_index'))
        else:
            return '内容和标题不能为空'


# 文章管理
@admin.route('/article/', methods=['GET', 'POST'])
def admin_article():
    if request.method == 'GET':
        uid = session.get('uid')
        if uid == None:
            return redirect(url_for('admin.admin_login'))
        page = request.args.get('page', 1, type=int)
        fid = request.args.get('id')
        # 获取栏目
        data = {}
        data['column'] = Column.query.all()
        column = Column.query.filter(Column.id == fid).first()
        # 每页显示条数
        per_page = 10
        if fid == None:
            pagination = Blog.query.order_by(Blog.id.desc()).paginate(page, per_page=per_page, error_out=False)
            posts = pagination.items
            fid = None

        else:
            pagination = Blog.query.filter(Blog.fid == fid).order_by(Blog.id.desc()).paginate(page, per_page=per_page,
                                                                                              error_out=False)
            posts = pagination.items
        return render_template('./admin/article.html', posts=posts, pagination=pagination, fid=fid, column=column,
                               data=data)


# 修改内容
@admin.route('/article/modify/<int:id>/', methods=['GET', 'POST'])
def article_modify(id):
    if request.method == 'GET':
        data = {}
        data['column'] = Column.query.all()
        data['blog'] = Blog.query.filter(Blog.id == id).first()
        return render_template('./admin/modify.html', data=data)
    else:
        fid = request.form.get('fid')
        title = request.form.get('title')
        content = request.form.get('content')
        blog = Blog.query.filter(Blog.id == id).first()
        blog.fid = fid
        blog.title = title
        blog.content = content
        db.session.add(blog)
        db.session.commit()
        return redirect(url_for('admin.admin_article', id=fid))


# 删除文章
@admin.route('/article/del/<int:id>/')
def article_del(id):
    if id != None:
        data = Blog.query.filter(Blog.id == id).first()
        db.session.delete(data)
        db.session.commit()
    return redirect(url_for('admin.admin_article', id=data.fid))


@admin.route('/youlian/', methods=['GET', 'POST'])
def admin_youlian():
    if request.method == 'GET':
        data = {}
        data['column'] = Column.query.all()
        data['youlian'] = Youlian.query.all()
        return render_template('./admin/youlian.html', data=data)
    else:
        title = request.form.get('title')
        url = request.form.get('url')
        data = Youlian()
        data.title = title
        data.url = url
        db.session.add(data)
        db.session.commit()
        return redirect(url_for('admin.admin_youlian'))


@admin.route('/youlian/del/<int:id>/')
def youlian_del(id):
    data = Youlian.query.filter(Youlian.id == id).first()
    db.session.delete(data)
    db.session.commit()
    return redirect(url_for('admin.admin_youlian'))


# 注销登录
@admin.route('/logout/')
def admin_logout():
    uid = session.get('uid')
    if uid == None:
        return redirect(url_for('admin.admin_login'))
    session.pop('uid', None)
    session.pop('user', None)
    return redirect(url_for('admin.admin_index'))
